package com.goparry.taskman.aws;

import java.io.File;

import com.amazonaws.services.s3.model.ObjectListing;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.goparry.taskman.GLOBAL;
import com.goparry.taskman.repository.TaskNote;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

public class AsyncAWSSaveNote extends AsyncTask<TaskNote, Integer, Void>{
	ProgressDialog mProgressDialog;
	Context mContext;
	
	public AsyncAWSSaveNote() {
		mContext = null;		
	}
	public AsyncAWSSaveNote(Context context) {
		mContext = context;		
	}

	public void initialize(Context context) {
		mContext = context;
	}
	@Override
	protected void onPreExecute() {
		if (mContext != null) {
	        mProgressDialog= new ProgressDialog(mContext);
	        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
	        mProgressDialog.setMessage("Loading task data...");
	        mProgressDialog.setIndeterminate(true);
			mProgressDialog.show();
		}
		super.onPreExecute();
	}
	protected Void doInBackground(TaskNote... arg0) {
		TaskNote taskNote = arg0[0];
		// Get the number of objects with this prefix
		// The saved file name will be <taskName><nObjects+1>.<format>
		ObjectListing objects = AWSUtils.getInstance().listObjects(GLOBAL.AWS_BUCKET, GLOBAL.AWS_PREFIX + taskNote.getTaskName());
		int nObjects = objects.getObjectSummaries().size() + 1;
		String key = GLOBAL.AWS_PREFIX + taskNote.getTaskName() + "/" + Integer.toString(nObjects);
		File file = new File(taskNote.getLocalUri());
		PutObjectRequest request = new PutObjectRequest(GLOBAL.AWS_BUCKET, key, file);
		ObjectMetadata metadata = new ObjectMetadata();
		metadata.addUserMetadata("name", taskNote.getName());
		metadata.addUserMetadata("author", taskNote.getAuthor());
		metadata.addUserMetadata("type", taskNote.getType());
		request.setMetadata(metadata);
		
		AWSUtils.getInstance().putObject(request);
		// Delete the file from the local device
		file.delete();
		return null;
	}
    protected void onProgressUpdate(Integer... progress) {
    	//mProgressDialog.setProgress(progress[0]);
    }
	@Override
	protected void onPostExecute(Void f) {
		if (mContext != null) {
			mProgressDialog.dismiss();
		}
		super.onPostExecute(null);
	}
}
